package cn.tedu.crm.user.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.tedu.crm.base.exception.ServiceException;
import cn.tedu.crm.dept.pojo.entity.Dept;
import cn.tedu.crm.operatelog.loggable.Loggable;
import cn.tedu.crm.operatelog.loggable.OperationModule;
import cn.tedu.crm.operatelog.loggable.OperationType;
import cn.tedu.crm.role.mapper.RoleMapper;
import cn.tedu.crm.role.pojo.entity.Role;
import cn.tedu.crm.user.mapper.UserMapper;
import cn.tedu.crm.user.mapper.UserRoleMapper;
import cn.tedu.crm.user.pojo.dto.UserLoginParam;
import cn.tedu.crm.user.pojo.dto.UserModuleQuery;
import cn.tedu.crm.user.pojo.dto.UserModuleSaveParam;
import cn.tedu.crm.user.pojo.dto.UserQuery;
import cn.tedu.crm.user.pojo.entity.User;
import cn.tedu.crm.user.pojo.entity.UserRole;
import cn.tedu.crm.user.pojo.vo.*;
import cn.tedu.crm.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Objects;


@Service
public class UserServiceImpl implements UserService{

    private static final Logger log = LoggerFactory.getLogger(UserServiceImpl.class);
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    @Loggable(module = OperationModule.USER_MANAGEMENT,type = OperationType.LOGIN)
    public UserLoginVO login(UserLoginParam param) {
        // 1.根据用户名查询用户信息
        User user = selectUserByUsername(param.getUsername());
        // 2.判断用户信息是否存在
        if (Objects.isNull(user)) {
            //  2.1.若不存在，说明用户名错误
            throw new ServiceException("用户名不存在");
        }
        //  2.2.若存在，接着判断密码是否正确
        if (!Objects.equals(user.getPassword(), param.getPassword())) {
            //   a.若密码不匹配，说明密码错误
            throw new ServiceException("密码不正确");
        }
        //   b.若密码匹配，登录成功，生成token，缓冲用户信息，封装vo返回
//        String token = UUID.randomUUID().toString();
//        user.setPassword(null);
//        redisTemplate.opsForValue().set(token, user);

        // 使用sa-token登录
        StpUtil.login(user.getId());
        StpUtil.getSession().set("username", user.getUsername());

        // 查询当前用户的权限列表
        List<String> permissionList = userMapper.selectPermissionListByUserId(user.getId());
        StpUtil.getSession().set("perms", permissionList);
        UserLoginVO userLoginVO = new UserLoginVO();
        userLoginVO.setToken(StpUtil.getTokenValue());
        userLoginVO.setUsername(user.getUsername());
        userLoginVO.setId(user.getId());
        userLoginVO.setAvatar(user.getAvatar());
        userLoginVO.setPerms(StpUtil.getPermissionList());
        return userLoginVO;
    }

    @Override
    public List<UserVO> selectUserList(UserQuery userQuery) {
        List<UserVO> userList = userMapper.selectUserList(userQuery);
        return userList;
    }

    @Override
    public List<UserModuleVO> selectUserModule(UserModuleQuery userModuleQuery) {
        List<UserModuleVO> list = userMapper.selectUserModule(userModuleQuery);
        return list;
    }

    @Transactional
    @Override
    @Loggable(module = OperationModule.USER_MANAGEMENT,type = OperationType.INSERT_UPDATE)
    public void saveUserModule(UserModuleSaveParam userModuleSaveParam) {
        User user = new User();
        BeanUtils.copyProperties(userModuleSaveParam,user);
        if(user.getId() == null  ){
            user.setCreateTime(new Date());
            user.setStatus(1);
            userMapper.insert(user);
        }else {
            user.setUpdateTime(new Date());
            userMapper.updateById(user);
            userRoleMapper.deleteByUserId(user.getId());
        }
        for (Long roleId : userModuleSaveParam.getRoleIds()) {
            UserRole userRole = new UserRole();
            userRole.setUserId(user.getId());
            userRole.setRoleId(roleId);
            userRoleMapper.insert(userRole);
        }
    }

    @Override
    public UserSelectVO selectUserById(Long id) {
        User user = userMapper.selectById(id);
        if(user == null){
            throw new ServiceException("用户不存在");
        }
        UserSelectVO userSelectVO = new UserSelectVO();
        BeanUtils.copyProperties(user,userSelectVO);
        List<Long> RoleIds = userRoleMapper.selectRoleIdsByUserId(id);
        userSelectVO.setRoleIds(RoleIds);
        return userSelectVO;
    }


    @Override
    @Loggable(module = OperationModule.USER_MANAGEMENT,type = OperationType.DELETE)
    public void deleteUser(List<Long> ids) {
        userMapper.deleteBatchIds(ids);
        userRoleMapper.delete(new QueryWrapper<UserRole>().in("user_id", ids));
    }

    @Override
    @Loggable(module = OperationModule.USER_MANAGEMENT,type = OperationType.UPDATE_PASSWORD)
    public void resetPassword(Long userId) {
        User user = userMapper.selectById(userId);
        if (user == null) {
            throw new ServiceException("用户不存在");
        }
        user.setPassword("123456");
        userMapper.updateById(user);
    }


    /**
     * 根据部门id查询部门人数
     * @param deptId
     * @return
     */
    @Override
    public Integer selectDeptCount(UserQuery query) {
        Integer peopleNum= userMapper.selectDeptCount(query);
       return peopleNum;
    }


    private User selectUserByUsername(String username) {
        QueryWrapper<User> qw = new QueryWrapper<>();
        qw.eq("username", username);
        return userMapper.selectOne(qw);
    }



}




